package models

import (
	"context"
	"elm_srv/cache"
	"elm_srv/elm"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

type Goods struct {
	gorm.Model
	ShopId int64   //商家ID
	Title  string  //商品标题
	Price  float64 //价格
	Stock  int64   //库存
}

func (g *Goods) GetGoodsById(goodsId int64) error {
	return DB.Where("id=?", goodsId).Limit(1).Find(&g).Error
}

func (g *Goods) CreateGoods() error {
	return DB.Create(&g).Error
}

func ListCart(userid int64) error {
	key := fmt.Sprintf("cart_%d_*", userid)
	keys := cache.Rdb.Keys(context.Background(), key).Val()

	if len(keys) == 0 {
		return nil
	}

	var listCart []*elm.CartList
	for _, s := range keys {
		goodsMap, _ := cache.Rdb.HGetAll(context.Background(), s).Result()

		goodsId, _ := strconv.Atoi(goodsMap["goods_id"])
		goodsPrice, _ := strconv.ParseFloat(goodsMap["goods_price"], 64)
		num, _ := strconv.Atoi(goodsMap["num"])

		listCart = append(listCart, &elm.CartList{
			UserId:     userid,
			GoodsId:    int64(goodsId),
			GoodsTitle: goodsMap["goods_title"],
			GoodsPrice: float32(goodsPrice),
			Num:        int64(num),
		})
	}
	return err
}
